package com.car.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @ClassName: FileUploadController
 * @Description:
 * @Author 余全盛
 * @Date: 2021/12/7 11:14
 */
@Controller
public class FileUploadController {

    @Autowired
    private Environment env;

    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> uploadFile(
            @RequestParam("uploadfile") MultipartFile file) {
        Map<String, String> map = new HashMap<String, String>();
        if (!file.isEmpty()) {
            try {
                // Get the filename and build the local file path
                //上传文件的名字
                String name = file.getOriginalFilename();
                //上传文件保存的名字
                String filename = name;
                String directory = env.getProperty("user.dir") + "\\src\\main\\resources\\static\\images";
                String filepath = Paths.get(directory, filename).toString();
                // Save the file locally
                BufferedOutputStream stream =
                        new BufferedOutputStream(new FileOutputStream(new File(filepath)));
                stream.write(file.getBytes());
                stream.close();
                map.put("flag", filename);
                return map;
            } catch (Exception e) {
                map.put("flag", "上传失败");
                return map;
            }
        } else {
            map.put("flag", "图片错误");
            return map;
        }
    }
}
